<?php require_once('start_session.php'); require_once('global_vars.php'); ?>
<link href="./css/tables.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="./js/json2.js"></script>
<script type="text/javascript" src="./js/jquery.tablesorter.min.js"></script>
<script type="text/javascript" src="./js/util.js"></script>
<script type="text/javascript">
	var surveyList = null;
	var MAX_TITLE = 20;
	var MAX_KEYWORD = 10;
	var userId = "<?php echo $_COOKIE['user_id']; ?>";
	const ADMIN_ID = "<?php echo ADMIN_ID ?>";
	
	$('document').ready(function( ) {
		$('table.sortable').tablesorter({widgets: ['zebra']});
		surveyList = $('#survey_list table tbody');
		printAllSurveyList();
	});
	function buildQuery(location, lat, lng, connectTime, memId, keyword) {
		var query = "";
		if (userId == ADMIN_ID) {
			if (keyword)
				query += "keyword="+keyword;
			return query;
		}

		if (location)
			query += "&location="+location;
		if (lat)
			query += "&latitude="+lat;
		if (lng)
			query += "&longitude="+lng;
		if (connectTime)
			query += "&connect_time="+connectTime;
		if (memId)
			query += "&mem_id="+memId;
		if (keyword)
			query += "&keyword="+keyword;
		return query.replace(/^&/, "");
	}
	function printAllSurveyList() {
		$('#search_cond').hide();
		var query = buildQuery("<?php echo $_SESSION['location']; ?>",
													"<?php echo $_SESSION['latitude']; ?>",
													"<?php echo $_SESSION['longitude']; ?>",
													printNow(), null, null);
		printSurveyListBy(query, false);
	}
	function printSurveyListBy(query, toAppend) {
		if (toAppend == false)
			surveyList.empty();
		
		if (typeof(query) == 'string')
			$.getJSON('get_survey_list.php', query, appendSurveys);	
		else
			$.postJSON('get_survey_list.php', query, appendSurveys);
	}
	function JSONtoString(object) {
		var results = [];
		for (var property in object) {
			var value = object[property];
			if (value)
				results.push(property.toString() + ': ' + value);
		}
		return '{' + results.join(', ') + '}';
	}
	function appendSurveys(data) {
		if (data.survey_list.length == 0) {
			surveyList.append("<tr><td colspan='10'>검색결과가 없습니다</td></tr>");
			return;
		}
		$.each(data.survey_list, function(list, survey) {
			var title = survey.title.substr(0, MAX_TITLE) + (survey.title.length > MAX_TITLE ? "..." : "");
			var keywords = "";
			for (var i = 0; i < survey.keywords.length; i++)
				keywords = keywords + survey.keywords[i] + ",";
			keywords = keywords.replace(/\,$/, "");
			keywords = keywords.substr(0, MAX_KEYWORD) + (keywords.length > MAX_KEYWORD ? "..." : "");
			
			var curTime = new Date();
			var startDate = new Date(survey.start_date);
			var endDate = new Date(survey.end_date);
			var startTime = new Date(printNowDate() + " " + survey.start_time);
			var endTime = new Date(printNowDate() + " " + survey.end_time);
			var canShow = survey.is_mid_result || endDate <= curTime; 
			var canEdit = (survey.member_id == userId && curTime < startDate) || (userId != "" && curTime > endDate);
			var canDelete = (survey.member_id == userId) && (curTime < startDate || curTime > endDate);
			var canLoad = curTime > endDate;
			if (userId == ADMIN_ID) {
				survey.is_joinable = false;
				canShow = true;
				canEdit = true;
				canDelete = true;
			}			
			surveyList.append("<tr" + (list%2==0 ? " class='even'" : "")+">"+
													"<td class=\"title\" onclick=\"openPopup('survey_info.php?sid="+survey.id+"', 'survey_info', 550, 450)\">"+title+"</td>"+
													"<td>"+survey.category+"</td>"+
													"<td>"+keywords+"</td>"+
													"<td>"+survey.view_count+"</td>"+
													"<td style=\"padding-left: 8px; text-align: left\">"+survey.start_date+" ~\n"+survey.end_date+"</td>"+
													"<td>"+survey.start_time+"~"+survey.end_time+"</td>"+
													"<td>"+(survey.is_joinable ?
														"<img class='poll clickable' src='./images/poll.png' title='참여하기' onclick='joinSurvey(this.parentNode.parentNode)' />" :
														"<img class='poll' src='./images/poll_d.png' title='설문에 참여할 수 없습니다' />")+
													"</td>"+
													"<td>"+(canShow ?
														"<img class='view clickable' src='./images/view.png' title='결과보기' onclick='showSurveyResult(this.parentNode.parentNode)' />" :
														"<img class='view' src='./images/view_d.png' title='설문결과를 볼 수 없습니다' />")+
													"</td>"+
													"<td>"+(canEdit ?
														"<img class='edit clickable' src='./images/edit.png' title='수정하기' onclick='editSurvey(this.parentNode.parentNode)'/>" :
														"<img class='edit' src='./images/edit_d.png' title='수정할 수 없습니다' />")+
													"</td>"+
													"<td>"+(canDelete ?
														"<img class='delete clickable' src='./images/delete.png' title='삭제하기' onclick='deleteSurvey(this.parentNode.parentNode)'/>" :
														"<img class='delete' src='./images/delete_d.png' title='삭제할 수 없습니다' />")+
													"</td>"+
													"<td>"+(canLoad ?
														"<img class='load clickable' src='./images/load.png' title='가져오기' onclick='loadSurvey(this.parentNode.parentNode)'/>" :
														"<img class='load' src='./images/load_d.png' title='가져올수 없습니다' />")+
													"</td>"+
													"<td class='id hide'>"+survey.id+"</td>"+
													"<td class='member_id hide'>"+survey.member_id+"</td>"+
												"</tr>");
		});
	}
	function joinSurvey(item) {
		var aSurvey = $(item);
		var survey_id = aSurvey.find('td.id').text();
		window.location = "survey_participate.php?sid="+survey_id;
		return false;
	}
	
	function showSurveyResult(item) {
		var aSurvey = $(item);
		var survey_id = aSurvey.find('td.id').text();
		window.location = "survey_viewresult.php?sid="+survey_id;
		return false;
	}

	function editSurvey(item) {
		var aSurvey = $(item);
		var survey_id = aSurvey.find('td.id').text();
		window.location = "survey_form.php?survey_id="+survey_id;
		return false;
	}
	function deleteSurvey(item) {
		var aSurvey = $(item);
		var survey_id = aSurvey.find('td.id').text();
		if (confirm("이 설문을 삭제하시겠습니까?")) {
			$.post("delete_survey.php", "survey_id="+survey_id, function(data) {
				aSurvey.remove();
				return false;
			});			
		}
	}
	function loadSurvey(item) {
		var aSurvey = $(item);
		var survey_id = aSurvey.find('td.id').text();
		window.location = "survey_load.php?survey_id="+survey_id;
		return false;
	}
</script>
<div id="search_cond">
<h3>검색조건</h3>
<div class="base"></div>
<div class="basic"></div>
</div>
<div id="survey_list">
<span id="show_all_survey_list"><a href="javascript:;" onclick="printAllSurveyList()">전체설문 보기(by 위치/시간조건)</a></span>
<h3>설문목록</h3>
<table class="sortable" border="0" cellspacing="0" cellpadding="0">
<thead>
	<tr>
		<th scope="col" width="35%">제목</th>
		<th scope="col" width="8.3%">카테고리</th>
		<th scope="col" width="10.6%">키워드</th>
		<th scope="col" width="5%">조회수</th>
		<th scope="col" width="13%">기간</th>
		<th scope="col" width="9%">시간대</th>
		<th scope="col" width="3.5%">참여</th>
		<th scope="col" width="3.5%">보기</th>
		<th scope="col" width="3.5%">수정</th>
		<th scope="col" width="3.5%">삭제</th>	
		<th scope="col" width="8.3%">가져오기</th>
	</tr>
</thead>
<tbody>
</tbody>
</table>
</div>